<template>
  <div class="live-detail">
    <div class="tabbar">
      <van-tabs v-model="active" sticky @rendered="onRendered" line-width="20px" line-height="4px">
        <van-tab title="直播">
          <div class="tab-container">
            <div class="live-summay">
              <div class="live-date-wrapper">
                <div class="live-date">
                  <p class="month">{{liveStage.stageDate && (liveStage.stageDate.slice(4,6).indexOf('0') === 0 ? liveStage.stageDate.slice(4,6).slice(1) : liveStage.stageDate.slice(4,6) )}}月</p>
                  <p class="date">{{liveStage.stageDate && (liveStage.stageDate.slice(6).indexOf('0') === 0 ? liveStage.stageDate.slice(6).slice(1) : liveStage.stageDate.slice(6))}}</p>
                </div>
              </div>
              <div class="live-item">
                <p>{{liveStage.summary}}</p>
              </div>
            </div>
            <timeline>
              <timeline-item v-for="content in liveContent" :key="content.id" :time="content.createTime.slice(11,16)">
                <div class="live-item">
                  <div @click="onContentClick" v-html="content.content"></div>
                </div>
              </timeline-item>
            </timeline>
          </div>
          <div class="live-detail-bottom">
            <div class="left">
              <van-image lazy-load  width="30px" height="30px" round :src="liveStage.tgInfo.avatar" class="avatar" @click.native="$router.push(`/adviser/detail/${liveStage.tgInfo.id}/`)" />
              <span class="name" @click="$router.push(`/adviser/detail/${liveStage.tgInfo.id}/`)" >{{liveStage.tgInfo.name}}</span>
            </div>
            <div class="right" @click="$router.push(`/live/${liveStage.liveId}/history/`)">
              <i v-if="liveStage.isLike === 1" class="icon icon-like-red" @click.stop="likeLiveStage(-1)"></i>
              <i v-else class="icon icon-like" @click.stop="likeLiveStage(1)"></i>
              <span style="margin-right: 20px;">{{liveStage.likeCount}}</span>
              <i class="icon icon-clock"></i>
              <span>历史直播</span>
            </div>
          </div>
        </van-tab>
        <van-tab title="互动">
          <div class="tab-container2">
            <div class="notice-box" @click="active = 0; showNotice=false;" v-if="showNotice">
              投顾发布了新的直播信息，点击查看！
            </div>
            <ul class="interaction-list">
              <li class="interaction-item van-hairline--bottom" v-for="(msg, i) in liveMessage" :key="i" >
                <template v-if="msg.tgContent">
                  <div class="item-top">
                    <van-image lazy-load round width="35px" height="35px" :src="liveStage.tgInfo.avatar" class="avatar" @click.native="$router.push(`/adviser/detail/${liveStage.tgInfo.id}/`)" />
                    <div class="info">
                      <div class="name">
                        <span>{{liveStage.tgInfo.name}}</span>
                        <i v-if="i == firstTgMsg" class="icon icon-live-corner" style="width: 12px; height: 12px;top: -1px;position: relative;"></i>
                      </div>
                    </div>
                    <p>{{msg.tgTime | publishTimeFormat}}</p>
                  </div>
                  <div class="item-body">
                    <p v-if="isFundLogin" class="reply">{{msg.tgContent}}</p>
                    <div class="login" v-else><i class="icon icon-warn"/>********** 内容登录可见，<a href="javascript:void(0)" @click="showContent">点击登录</a></div>
                    <div class="ask" v-if="msg.userContent">{{msg.userName | mobileFormat}}：{{msg.userContent}}</div>
                  </div>
                </template>
                <template v-else>
                  <div class="item-top">
                    <van-image lazy-load round width="35px" height="35px" :src="user.avatar || 'user.png'" class="avatar"/>
                    <div class="info">
                      <div class="name">
                        <span>{{user.mobile | mobileFormat}}</span>
                      </div>
                    </div>
                    <p>{{msg.userTime | publishTimeFormat}}</p>
                  </div>
                  <div class="item-body" style="margin-top: 10px;">
                    <p class="reply">{{msg.userContent}}</p>
                  </div>
                </template>
              </li>
            </ul>
          </div>
          <div class="input-wrapper">
            <div class="bottom-notice">
              风险提示：投资顾问提供的观点和投资建议仅供参考，市场有风险，投资需谨慎。
            </div>
            <div class="input-box">
              <van-field
                class="input"
                v-model="message"
                rows="1"
                :autosize="{maxHeight: 100}"
                type="textarea"
                @click="onInputClick"
                placeholder="我也说两句"
              />
              <div class="btn-wrapper">
                <van-button van-button plain round @click="sendLiveMsg">发 送</van-button>
              </div>
            </div>
          </div>
        </van-tab>
        <van-tab title="" disabled></van-tab>
        <van-tab title="1" disabled>
          <template #title>
            <div class="read-count">
              <i class="icon icon-follow" style="margin-right: 10px;"></i>
              <span style="font-size: 12px;">{{liveStage.readCount || 0}}</span>
            </div>
          </template>
        </van-tab>
      </van-tabs>
    </div>
    <van-dialog
      v-model="showRiskAlert"
      title='风险提示'
      confirmButtonText='知道了'
      confirmButtonColor='#EB4339'
      messageAlign= 'left'
      closeOnPopstate
    >
      <div class="van-dialog__message--left van-hairline--top">
        <p>尊敬的投资者您好，感谢您关注直播版块，温馨提示您主播观点仅供参考，不作为您买入和卖出的操作建议，版块中发言者都有其特定立场，投资者应当经过独立思考做出投资决策，而不应当以任何信息取代独立判断。市场有风险，投资须谨慎。</p>
        <br/>
        <p style="color: #EB4339;">郑重声明：投资者依版块中信息投资所引发或可能引发的任何损失由投资者自行承担。</p>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import { Dialog, Tab, Tabs, Tag, Field, Button, Toast, ImagePreview } from 'vant';
import Timeline from '../../components/Timeline';
import TimelineItem from '../../components/TimelineItem';
import { getLiveStage, pageLiveContentApp, sendLiveMsgApp, pageLiveMsgApp, likeLiveStage } from '../../api/live';
import trim from 'lodash/trim';
import dayjs from 'dayjs';

export default {
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Tag.name]: Tag,
    [Field.name]: Field,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    Timeline,
    TimelineItem
  },

  props: {
    stageId: {
      type: String
    }
  },

  data() {
    return {
      imageDialog: '',
      active: 0,
      showRiskAlert: false,
      showNotice: false,
      liveStage: {
        tgInfo: {}
      },
      liveContent: [],
      liveMessage: [],
      loading: false,
      content: {
        size: 10,
      },
      msg: {
        size: 10
      },
      message: '',
      lastSendTime: 0
    }
  },

  created() {
    document.body.style.backgroundColor="#fff";
  },

  mounted() {
    this.getLiveStage().then(() => this.showAlert());
    this.$bus.$on('reachBottom', this.reachBottom.bind(this));
    if (this.isLogin) {
       this.$store.dispatch('getUserInfo');
    }
    this.$bus.$on('refreshPage', () => {
      if (this.isLogin) {
        this.$store.dispatch('getUserInfo');
      }
    })
  },

  beforeDestroy() {
    clearInterval(this.timerId);
    clearInterval(this.timerId2);
    this.$bus.$off('reachBottom');
    if(this.imageDialog !== ''){
      this.imageDialog.close();
    }
  },

  filters: {
    mobileFormat(mobile) {
      return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
    }
  },

  computed: {
    ...mapState(['user']),
    ...mapGetters(['isLogin', 'isFundLogin']),
    firstTgMsg() {
      return this.liveMessage.findIndex(item => Boolean(item.tgContent));
    }
  },

  methods: {
    ...mapActions(['login', 'fundLogin']),

    showAlert() {
      const key = `${this.liveStage.liveId}-${this.stageId}-${dayjs().format('YYYYMMDD')}`;

      if(!localStorage.getItem(key)) {
        this.showRiskAlert = true
        localStorage.setItem(key, 'true');
      }
    },

    async getLiveStage() {
      const data = await getLiveStage(this.stageId);
      this.liveStage = data.data;
      this.$setTitle(`${data.data.tgInfo.name}的直播间`);
    },

    async pageLiveContentApp() {
      const lastIndex = this.liveContent.length - 1;
      const data = await pageLiveContentApp({
        offset: this.liveContent[lastIndex] ? 1 : 0,
        start: this.liveContent[lastIndex] ? this.liveContent[lastIndex].id : 0,
        size: this.content.size,
        stageId: this.stageId,
        direction: 2,
      });
      this.liveContent = data.list;
      this.timerId = setInterval(async () => {
        if(this.liveStage.status === 1) {
          const data = await pageLiveContentApp({
            offset: 1,
            start: this.liveContent[0] ? this.liveContent[0].id : 0,
            size: this.content.size,
            stageId: this.stageId,
            direction: 1,
          });
          console.log(data.list);
          if(data.list.length) {
            this.showNotice = true;
            this.liveContent.unshift(...data.list.reverse());
          }
        }
      }, 30 * 1000);
    },

    async pageLiveMsgApp() {
      const lastIndex = this.liveMessage.length - 1;
      const data = await pageLiveMsgApp({
        offset: this.liveMessage[lastIndex] ? 1 : 0,
        start: this.liveMessage[lastIndex] ? this.liveMessage[lastIndex].id : 0,
        size: this.msg.size,
        stageId: this.stageId,
        direction: 2,
      });
      this.liveMessage = data.list;
      this.timerId2 = setInterval(async () => {
        if(this.liveStage.status === 1) {
          const data = await pageLiveMsgApp({
            offset: this.liveMessage[0] ? 1 : 0,
            start: this.liveMessage[0] ? this.liveMessage[0].id : 0,
            size: this.content.size,
            stageId: this.stageId,
            direction: 1,
          });
          console.log(data.list);
          if(data.list.length) {
            this.liveMessage.unshift(...data.list.reverse());
          }
        }
      }, 30 * 1000);
    },

    reachBottom() {
      this.active === 0 ? this.loadLiveContent() : this.loadLiveMessage();
    },

    async loadLiveContent() {
      try {
        this.loading = true;
        const lastIndex = this.liveContent.length - 1;
        const data = await pageLiveContentApp({
          offset: this.liveContent[lastIndex] ? 1 : 0,
          start: this.liveContent[lastIndex] ? this.liveContent[lastIndex].id : 0,
          size: this.content.size,
          stageId: this.stageId,
          direction: 2,
        });
        this.liveContent = this.liveContent.concat(data.list);
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async loadLiveMessage() {
      try {
        this.loading = true;
        const lastIndex = this.liveMessage.length - 1;
        const data = await pageLiveMsgApp({
          offset: this.liveMessage[lastIndex] ? 1 : 0,
          start: this.liveMessage[lastIndex] ? this.liveMessage[lastIndex].id : 0,
          size: this.msg.size,
          stageId: this.stageId,
          direction: 2,
        });
        this.liveMessage = this.liveMessage.concat(data.list);
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async sendLiveMsg() {
      if(!trim(this.message)) {
        Toast({
          message: '输入内容不能为空',
          position: 'bottom'
        })
        return;
      }
      if(dayjs().diff(dayjs(this.lastSendTime), 'm')  < 1) {
        Toast({
          message: '发言太频繁，请稍后再试',
          position: 'bottom'
        })
        return;
      }
      if(this.liveStage.status !== 1) {
        Toast({
          message: '直播已关闭',
          position: 'bottom'
        })
        return;
      }
      const message = {
        userContent: this.message,
        userTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        stageId: this.stageId,
        tgId: this.liveStage.tgId,
        tgInfo: this.liveStage.tgInfo,
      };
      this.message = '';
      this.lastSendTime = Date.now();
      const data = await sendLiveMsgApp(message);
      if(data.code === 0) {
        message.id = data.id;
        this.liveMessage.unshift(message);
        Toast({
          message: '发送成功, 请耐心等待',
          position: 'bottom'
        });
      }
    },

    onRendered(name, title) {
      if(this.active === 1) {
        this.pageLiveMsgApp();
      } else {
        this.pageLiveContentApp();
      }
    },

    onInputClick() {
      if(!this.isFundLogin) {
        return this.fundLogin();
      }
    },

    async likeLiveStage(isLike) {
      if(!this.isLogin) {
        return this.login();
      }
      const data = await likeLiveStage(this.stageId, isLike);
      if (data.code === 0) {

        if(isLike === 1) {
          this.liveStage.likeCount = this.liveStage.likeCount + 1;
          this.liveStage.isLike = 1;
          this.$toast('点赞成功');
        } else {
          this.liveStage.likeCount = this.liveStage.likeCount - 1;
          this.liveStage.isLike = -1;
          this.$toast('取消点赞成功');
        }
      }
    },

    onContentClick(e) {
      console.log(arguments)
      if(e.target.tagName === 'IMG') {
        this.imageDialog = ImagePreview([
          e.target.src.replace('/resize', '')
        ])
      } else {
        try {
          const id = e.target.parentNode.attributes['data-id'].value
          const type = e.target.parentNode.attributes['data-type'].value
          if (type === '2') {
            this.$router.push(`/view/detail/${id}`);
          } else if (type === '3') {
            this.$router.push(`/portfolio/detail/${id}`);
          } else if (type === '4') {
            this.$router.push(`/service/detail/${id}`);
          }
        } catch (error) {

        }
      }
    },

    showContent() {
      if(!this.isLogin) {
        return this.login();
      }
      if(!this.isFundLogin) {
        return this.fundLogin().then(() =>{
          this.pageLiveContentApp();
        });
      }
    }
  }
}
</script>

<style lang="less">

.live-detail {
  padding-bottom: 70px;

  .tabbar {
    .van-tab__text {
      font-size: 16px;
    }

    .read-count {
      display: flex;
      align-items: center;
      float: right;
      padding-right: 15px;
    }

    .van-tab__text {
      display: unset;
    }
  }
  .tab-container {
    background-color: #fff;
    border-top: 10px solid #f5f6f6;
    padding: 15px 15px 15px 0;
  }

  .tab-container2 {
    margin-bottom: 130px;
    .notice-box {
      background-color: rgba(235, 67, 57, 0.8);
      text-align: center;
      color: #fff;
      font-size: 14px;
      padding: 5px 0;
      position: fixed;
      top: 44px;
      left: 0;
      right: 0;
      z-index: 2;
    }
  }

  .live-item {
    background: #F5F6F6;
    border-radius: 4px;
    border-radius:4px;
    padding: 15px;
    line-height: 1.4;

    & /deep/ .wscnph {
      width: 100%;
    }

    * {
     max-width: 100% !important;
     word-break: break-all;
    }

    ol {
      list-style: decimal;
    }

    ul {
      list-style: unset;
    }

    li {
      margin-left: 20px;
    }
  }

  .live-summay {
    margin-bottom: 15px;
    display: flex;
    align-items: center;

    .live-date-wrapper {
      padding: 8px 10px;
      width: 60px;

      .live-date {
        border: 1px solid #eb4339;
        border-radius: 4px;
        text-align: center;

        .month {
          color: #fff;
          background-image: linear-gradient(90deg, #ED7F31 0%, #E8302E 92%);
          font-size: 12px;
          padding: 3px;
        }

        .date {
          padding: 4px 8px;
          font-size: 20px;
          color: #eb4339;
        }
      }
    }

    .live-item {
      flex: 1;
      color: #eb4339;
      background: url('../../assets/live-bg2x.png');
      background-size: cover;
    }
  }

  .live-detail-bottom {
    background: #fff;
    box-shadow: 0 -1px 10px 0 rgba(0,0,0,0.15);
    display: flex;
    align-items: center;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 15px 12px;
    color: #999;
    z-index: 3;

    .avatar {
      border-radius: 50%;
      width: 30px;
      height: 30px;
    }

    .left {
      flex: 1;
      display: flex;
      align-items: center;

      .name {
        font-weight: bold;
        color: #333;
        padding: 0 10px;
        margin-right: 15px;
        font-size: 16px;
      }
    }

    .right {
      color: #000;
      font-size: 14px;
      display: flex;
      align-items: center;
    }
  }

  .interaction-list {
    background-color: #fff;
    .avatar {
      margin-right: 10px;
    }

    .interaction-item {
      padding: 15px;
      .item-top {
        display: flex;
        align-items: center;

        .info {
          .name {
            display: flex;
            align-items:center;
          }
          span {
            color: #121d32;
            font-size: 12px;
            margin-right: 5px;
          }
        }

        p {
          color: #c3c4ca;
          font-size: 12px;
          line-height: 20px;
          flex: 1;
          text-align: right;
        }

      }

      .item-body {
        .reply, .login {
          margin: 10px 0;
          line-height: 1.41;
        }

        .login {
          color: #2b313d;
          font-display: 14px;

          a {
            color: #eb4339;
          }
        }

        .ask {
          background-color: #f5f5f5;
          color: #666;
          border-radius: 4px;
          padding: 10px;
          position: relative;
        }
      }
    }
  }

  .bottom-notice {
    background-color: #fde2c5;
    color: #eb4339;
    font-size: 12px;
    padding: 10px 15px;
    line-height: 1.3;
  }

  .input-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
  }

  .input-box {
    background: #fff;
    display: flex;
    align-items: center;
    width: 100%;
    padding: 8px 12px;
    white-space: nowrap;
  }

  .btn-wrapper {
    margin-left: 20px;

    .van-button__text {
      padding: 0 5px;
    }

    .van-button--round {
      border-radius: 40px;
      border-color: #5e616b;
    }
  }

  .input {
    border-radius: 4px;
    background: #f5f6f6;
  }
}

.van-dialog {
  border-radius: 10px;
}

.van-dialog__header {
  padding: 10px 0;
  font-size: 18px;
}

.van-dialog__message--left {
  text-align: left;
  font-size: 14px;
  color: #5e616b;
  line-height: 1.5;
  padding: 10px 20px 30px 20px;
}
</style>
